﻿using Oliving.Edge.Common;
using Oliving.Edge.Common.DB;
using Oliving.Edge.Common.Helper;
using Oliving.Edge.Model.Common;
using Oliving.Edge.Model.Models.MQXT;
using Oliving.Edge.Model.Models.SystemBase;
using Oliving.Edge.Model.Models.User;
using Oliving.Edge.Model.Models.XLT;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Oliving.Edge.Model.Models
{
    public class DBSeed
    {
        // 这是我的在线demo数据，比较多，且杂乱
        // gitee 源数据
        private static string SeedDataFolder = "BlogCore.Data.json/{0}.tsv";


        // 这里我把重要的权限数据提出来的精简版，默认一个Admin_Role + 一个管理员用户，
        // 然后就是菜单+接口+权限分配，注意没有其他博客信息了，下边seeddata 的时候，删掉即可。

        // gitee 源数据
        private static string SeedDataFolderMini = "BlogCore.Mini.Data.json/{0}.tsv";

        // gitee 源数据
        private static string SeedDataFolderEdge = "Edge.Data.json/{0}.tsv";


        /// <summary>
        /// 异步添加种子数据
        /// </summary>
        /// <param name="myContext"></param>
        /// <param name="WebRootPath"></param>
        /// <returns></returns>
        public static async Task SeedAsync(MyContext myContext, string WebRootPath)
        {
            try
            {
                if (string.IsNullOrEmpty(WebRootPath))
                {
                    throw new Exception("获取wwwroot路径时，异常！");
                }

                SeedDataFolder = Path.Combine(WebRootPath, SeedDataFolderEdge);
                //SeedDataFolder = Path.Combine(WebRootPath, SeedDataFolder);
                SeedDataFolderMini = Path.Combine(WebRootPath, SeedDataFolderMini);

                Console.WriteLine("Config data init...");
                Console.WriteLine($"Is multi-DataBase: {Appsettings.app(new string[] { "MutiDBEnabled" })}");
                if (Appsettings.app(new string[] { "MutiDBEnabled" }).ObjToBool())
                {
                    Console.WriteLine($"Master DB Type: {MyContext.DbType}");
                    Console.WriteLine($"Master DB ConnectString: {MyContext.ConnectionString}");
                    Console.WriteLine();

                    var slaveIndex = 0;
                    BaseDBConfig.MutiConnectionString.Where(x => x.ConnId != MainDb.CurrentDbConnId).ToList().ForEach(m =>
                    {
                        slaveIndex++;
                        Console.WriteLine($"Slave{slaveIndex} DB ID: {m.ConnId}");
                        Console.WriteLine($"Slave{slaveIndex} DB Type: {m.DbType}");
                        Console.WriteLine($"Slave{slaveIndex} DB ConnectString: {m.Conn}");
                    });

                }
                else
                {
                    Console.WriteLine("DB Type: " + MyContext.DbType);
                    Console.WriteLine("DB ConnectString: " + MyContext.ConnectionString);
                }

                var rrr = myContext.Db.Ado.Connection;

                Console.WriteLine("Create Database...");
                // 创建数据库
                myContext.Db.DbMaintenance.CreateDatabase();

                Console.WriteLine("Create Tables...");
                #region MyRegion

                // 创建表
                myContext.CreateTableByEntity(false,
                    typeof(Advertisement),
                    typeof(BlogArticle),
                    typeof(Guestbook),
                    typeof(Module),
                    typeof(ModulePermission),
                    typeof(OperateLog),
                    typeof(PasswordLib),
                    typeof(Permission),
                    typeof(Role),
                    typeof(RoleModulePermission),
                    typeof(sysUserInfo),
                    typeof(Topic),
                    typeof(TopicDetail),
                    typeof(UserRole)


                    , typeof(CaiJiQiModelValue)
                    , typeof(MQXT_CaiJiQiModel)
                    , typeof(MQXT_DataShowModel)
                    , typeof(MQXT_JiZhongQiModel)

                  //,
                  //  typeof(Sys_DataDictionary)   // 数据字典
                  //, typeof(Sys_Dept)   // 测试  

                  //, typeof(Nlog_Log_202003)   // 测试    日期 2020年3月5日  
                  //, typeof(sys_config)       // 新增表  日期 2020年2月17日  
                  //, typeof(SysDepartmentModel)  // 新增表  日期 2020年2月17日 

                #region 大同

                  //, typeof(DTSN_Canning)
                  //, typeof(DTSN_ShangWeiJi)
                  //, typeof(DTSN_TongDao)
                  //, typeof(DTSN_TongDaoConfig)
                  //, typeof(DTSN_CanningRecord)
                  //  typeof(DTSN_WuAPI_202004)

                #endregion


                  , typeof(SysFile)


                #region  效率通
                //WY_Project WY_Company

                , typeof(WY_Company)       // 公司管理

                , typeof(WY_Project)       // 项目管理 




                #endregion




                    );


                #endregion


                // 后期单独处理某些表
                // myContext.Db.CodeFirst.InitTables(typeof(sysUserInfo));

                Console.WriteLine("Database is  created success!");
                Console.WriteLine();

                if (Appsettings.app(new string[] { "AppSettings", "SeedDBDataEnabled" }).ObjToBool())
                {
                    Console.WriteLine("Seeding database...");
                    bool isExist = false;

                    #region Blog
                    if (false)
                    {
                        #region BlogArticle
                        //if (!await myContext.Db.Queryable<BlogArticle>().AnyAsync())
                        //{
                        //    List<BlogArticle> a = JsonHelper.ParseFormByJson<List<BlogArticle>>(FileHelper.ReadFile(string.Format(SeedDataFolder, "BlogArticle"), Encoding.UTF8));
                        //    myContext.GetEntityDB<BlogArticle>().InsertRange(a);
                        //    Console.WriteLine("Table:BlogArticle created success!");
                        //}
                        //else
                        //{
                        //    Console.WriteLine("Table:BlogArticle already exists...");
                        //}
                        #endregion

                        #region Topic
                        //if (!await myContext.Db.Queryable<Topic>().AnyAsync())
                        //{
                        //    myContext.GetEntityDB<Topic>().InsertRange(JsonHelper.ParseFormByJson<List<Topic>>(FileHelper.ReadFile(string.Format(SeedDataFolder, "Topic"), Encoding.UTF8)));
                        //    Console.WriteLine("Table:Topic created success!");
                        //}
                        //else
                        //{
                        //    Console.WriteLine("Table:Topic already exists...");
                        //}
                        #endregion

                        #region TopicDetail
                        //if (!await myContext.Db.Queryable<TopicDetail>().AnyAsync())
                        //{
                        //    myContext.GetEntityDB<TopicDetail>().InsertRange(JsonHelper.ParseFormByJson<List<TopicDetail>>(FileHelper.ReadFile(string.Format(SeedDataFolder, "TopicDetail"), Encoding.UTF8)));
                        //    Console.WriteLine("Table:TopicDetail created success!");
                        //}
                        //else
                        //{
                        //    Console.WriteLine("Table:TopicDetail already exists...");
                        //}
                        #endregion
                    }
                    #endregion

                    #region BaseSystem

                    #region Module
                    if (!await myContext.Db.Queryable<Module>().AnyAsync())
                    {
                        // Sys_Module     Module   

                        //string tableName = ModelReflectionHelper.GetModelTableName<Module>(); ;
                        //if (!string.IsNullOrEmpty(tableName))
                        //{ 
                        //    string dataContext = FileHelper.ReadFile(string.Format(SeedDataFolder, tableName), Encoding.UTF8, out isExist);
                        //    if (isExist)
                        //    {
                        //        List<Module> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Module>>(dataContext);
                        //        myContext.GetEntityDB<Module>().InsertRange(list);
                        //        Console.WriteLine("Table:Module created success!");
                        //    }
                        //}


                        CreateData<Module>(myContext);

                    }
                    else
                    {
                        Console.WriteLine("Table:Module already exists...");
                    }
                    #endregion

                    #region Permission
                    if (!await myContext.Db.Queryable<Permission>().AnyAsync())
                    {
                        //string tableName = ModelReflectionHelper.GetModelTableName<Permission>(); ;
                        //if (!string.IsNullOrEmpty(tableName))
                        //{
                        //    string dataContext = FileHelper.ReadFile(string.Format(SeedDataFolder, tableName), Encoding.UTF8, out isExist);
                        //    if (isExist)
                        //    {
                        //        List<Permission> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Permission>>(dataContext);
                        //        myContext.GetEntityDB<Permission>().InsertRange(list);
                        //        Console.WriteLine("Table:Permission created success!");
                        //    } 
                        //}

                        CreateData<Permission>(myContext);
                    }
                    else
                    {
                        Console.WriteLine("Table:Permission already exists...");
                    }
                    #endregion

                    #region Role
                    if (!await myContext.Db.Queryable<Role>().AnyAsync())
                    {
                        #region old 
                        //myContext.GetEntityDB<Role>().InsertRange(JsonHelper.ParseFormByJson<List<Role>>(FileHelper.ReadFile(string.Format(SeedDataFolder, "Role"), Encoding.UTF8)));
                        //Console.WriteLine("Table:Role created success!");
                        #endregion

                        //string tableName = ModelReflectionHelper.GetModelTableName<Role>(); ;
                        //if (!string.IsNullOrEmpty(tableName))
                        //{
                        //    string dataContext = FileHelper.ReadFile(string.Format(SeedDataFolder, tableName), Encoding.UTF8, out isExist);
                        //    if (isExist)
                        //    {
                        //        List<Role> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Role>>(dataContext);
                        //        myContext.GetEntityDB<Role>().InsertRange(list);
                        //        Console.WriteLine("Table:Role created success!");
                        //    }
                        //}

                        CreateData<Role>(myContext);
                    }
                    else
                    {
                        Console.WriteLine("Table:Role already exists...");
                    }
                    #endregion

                    #region RoleModulePermission
                    if (!await myContext.Db.Queryable<RoleModulePermission>().AnyAsync())
                    {
                        #region MyRegion
                        //myContext.GetEntityDB<RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson<List<RoleModulePermission>>(FileHelper.ReadFile(string.Format(SeedDataFolder, "RoleModulePermission"), Encoding.UTF8)));
                        //Console.WriteLine("Table:RoleModulePermission created success!");
                        #endregion



                        CreateData<RoleModulePermission>(myContext);
                        //string tableName = ModelReflectionHelper.GetModelTableName<RoleModulePermission>(); ;
                        //if (!string.IsNullOrEmpty(tableName))
                        //{ 
                        //    string dataContext = FileHelper.ReadFile(string.Format(SeedDataFolder, tableName), Encoding.UTF8, out isExist);
                        //    if (isExist)
                        //    { 
                        //        List<RoleModulePermission> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RoleModulePermission>>(dataContext);
                        //        myContext.GetEntityDB<RoleModulePermission>().InsertRange(list);
                        //        Console.WriteLine("Table:RoleModulePermission created success!");
                        //    } 
                        //}

                    }
                    else
                    {
                        Console.WriteLine("Table:RoleModulePermission already exists...");
                    }
                    #endregion

                    #region UserRole
                    if (!await myContext.Db.Queryable<UserRole>().AnyAsync())
                    {
                        #region MyRegion

                        //myContext.GetEntityDB<UserRole>().InsertRange(JsonHelper.ParseFormByJson<List<UserRole>>(FileHelper.ReadFile(string.Format(SeedDataFolder, "UserRole"), Encoding.UTF8)));
                        //Console.WriteLine("Table:UserRole created success!");

                        #endregion

                        //string tableName = ModelReflectionHelper.GetModelTableName<UserRole>(); ;
                        //if (!string.IsNullOrEmpty(tableName))
                        //{
                        //    //string dataContent = FileHelper.ReadFile(string.Format(SeedDataFolder, tableName), Encoding.UTF8);
                        //    //List<UserRole> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<UserRole>>(dataContent);
                        //    //myContext.GetEntityDB<UserRole>().InsertRange(list);
                        //    //Console.WriteLine("Table:UserRole created success!");
                        //}

                        CreateData<UserRole>(myContext);
                    }
                    else
                    {
                        Console.WriteLine("Table:UserRole already exists...");
                    }
                    #endregion

                    #region sysUserInfo
                    if (!await myContext.Db.Queryable<sysUserInfo>().AnyAsync())
                    {
                        #region MyRegion

                        //myContext.GetEntityDB<sysUserInfo>().InsertRange(JsonHelper.ParseFormByJson<List<sysUserInfo>>(FileHelper.ReadFile(string.Format(SeedDataFolder, "sysUserInfo"), Encoding.UTF8)));
                        //Console.WriteLine("Table:sysUserInfo created success!");
                        #endregion


                        CreateData<sysUserInfo>(myContext);

                        //string tableName = ModelReflectionHelper.GetModelTableName<sysUserInfo>(); ;
                        //if (!string.IsNullOrEmpty(tableName))
                        //{
                        //    string dataContent = FileHelper.ReadFile(string.Format(SeedDataFolder, tableName), Encoding.UTF8);
                        //    List<sysUserInfo> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<sysUserInfo>>(dataContent);
                        //    myContext.GetEntityDB<sysUserInfo>().InsertRange(list);
                        //    Console.WriteLine("Table:sysUserInfo created success!");
                        //}

                    }
                    else
                    {
                        Console.WriteLine("Table:sysUserInfo already exists...");
                    }
                    #endregion

                    #endregion
                     

                    // ================================================================================================= System  ====
                     

                    Console.WriteLine("Done seeding database.");
                }

                Console.WriteLine();

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static void CreateData<T>(MyContext myContext) where T : class, new()
        {
            string tableName = ModelReflectionHelper.GetModelTableName<T>(); ;
            if (!string.IsNullOrEmpty(tableName))
            {
                bool isExist = false;
                string dataContext = FileHelper.ReadFile(string.Format(SeedDataFolder, tableName), Encoding.UTF8, out isExist);
                if (isExist)
                {
                    List<T> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<T>>(dataContext);
                    myContext.GetEntityDB<T>().InsertRange(list);
                    Console.WriteLine("Table:" + tableName + " created success!");
                }

            }
        }

    }
}
